package com.kaibes.web.filter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class FilterInternalConfig implements WebMvcConfigurer {

	private List<String> resourcesWhiteList = new ArrayList<>();
	{
		resourcesWhiteList.add(".js");
		resourcesWhiteList.add(".css");
		resourcesWhiteList.add(".html");
		resourcesWhiteList.add(".ico");
		resourcesWhiteList.add(".map");
		resourcesWhiteList.add(".woff2");
		resourcesWhiteList.add(".gif");
		resourcesWhiteList.add(".jpg");
		resourcesWhiteList.add(".png");
	}
	private List<String> pathWhiteStartList = new ArrayList<>();
	private List<String> pathWhiteList = new ArrayList<>();
	
	public List<String> getResourcesWhiteList() {
		return resourcesWhiteList;
	}

	public List<String> getPathWhiteStartList() {
		return pathWhiteStartList;
	}

	public List<String> getPathWhiteList() {
		return pathWhiteList;
	}
	
	@Autowired
    private ApplicationContext applicationContext;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<BasicInterceptor> basicInterceptors = new ArrayList<>();
        basicInterceptors.addAll(applicationContext.getBeansOfType(BasicInterceptor.class).values());
        Collections.sort(basicInterceptors, new Comparator<BasicInterceptor>() {

            @Override
            public int compare(BasicInterceptor o1, BasicInterceptor o2) {
                return o2.order()-o1.order();
            }
        });
        basicInterceptors.forEach(interceptor->{
            if (interceptor.patterns() == null) {
                registry.addInterceptor(interceptor);
            } else {
                registry.addInterceptor(interceptor).addPathPatterns(interceptor.patterns());
            }
        });
    }
	
}
